package com.tony.boot.resolver;

import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import com.tony.boot.entity.Author;
import com.tony.boot.entity.Book;
import com.tony.boot.entity.BookInput;
import com.tony.boot.exception.BookNotFoundException;
import com.tony.boot.repository.AuthorRepository;
import com.tony.boot.repository.BookRepository;

import java.util.HashSet;
import java.util.Set;

public class Mutation implements GraphQLMutationResolver{
    private BookRepository bookRepository;
    private AuthorRepository authorRepository;

    public Mutation(AuthorRepository authorRepository, BookRepository bookRepository) {
        this.authorRepository = authorRepository;
        this.bookRepository = bookRepository;
    }
    public Author newAuthor(String name, Integer bookId){
        Author author = new Author();
        Set<Book> books = new HashSet<>();
        books.add(new Book(bookId));
        author.setBooks(books);
        author.setName(name);
        return authorRepository.save(author);
    }

    public Book newBook(BookInput bookInput) {
        Book book = new Book();
        Set<Author> authors = new HashSet<>();
        for (Integer id: bookInput.getAuthors()) {
            authors.add(new Author(id));
        }
        book.setAuthors(authors);
        book.setName(bookInput.getName());
        return bookRepository.save(book);
    }

    public boolean deleteBook(Integer id) {
        bookRepository.deleteById(id);
        return true;
    }
    public Book updateBookName(Integer id, String name) {
        Book book = bookRepository.findById(id).get();
        if(book == null) {
            throw new BookNotFoundException("The book to be updated was not found", id);
        }
        book.setName(name);
        return bookRepository.save(book);
    }
}
